import axios from 'axios'
import { ElLoading } from 'element-plus'

var loading = null
let upload_url = null
if (process.env.NODE_ENV === 'development') {
    upload_url = '/url'
} else {
    upload_url = '/'
}

const upload = axios.create({
    baseURL: upload_url,
    headers: {
        'Content-Type': 'multipart/form-data',
    },
    timeout: 10000,
})
// 发送请求前拦载
upload.interceptors.request.use(
    (config) => {
        loading = ElLoading.service({
            lock: true,
            text: '图片正在上传',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        config.headers['Access-Control-Allow-Origin'] = '*'
        let Authorization = ''
        let loc_ses = localStorage.getItem('loc_ses')
        // console.log('是否保持登录', loc_ses)
        if (loc_ses == 'true') {
            Authorization = localStorage.getItem('Authorization')
        } else {
            Authorization = sessionStorage.getItem('Authorization')
        }
        
        config.headers['Authorization'] = Authorization || ''
        return config
    },
    (error) => {
        loading.close()
        return Promise.reject(error)
    }
)

//发送请求返回拦载
upload.interceptors.response.use(
    function (res) {
        loading.close()
        // 对响应数据做点什么
        var data = res.data
        // console.log('响应成功', data)
        if (data.code == 1) {
            return res.data
        } else {
            return res.data
        }
    },
    function (error) {
        // 对响应错误做点什么
        console.log('响应失败', error)
        loading.close()
        return error
    }
)

export default upload
